import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @program: 2022.1.22堆
 * @description:
 * @author: 李鑫月
 * @create: 2022-01-22 10:20
 **/
public class TestHeap {
    public  int[] elem;
    public  int usedsize;
    public  TestHeap(){
        this.elem=new int[10];
    }
    public void change(int parent,int child,int[] elem){
        int tmp=elem[parent];
        elem[parent]=elem[child];
        elem[child]=tmp;
    }
    public void shiftDown(int parent,int len){
        int child=2*parent+1;
        //至少有一个左孩子
        while (child<len){
            if(child+1<len&&elem[child]<elem[child+1]){
                child++;
            }
            if(elem[parent]<elem[child]){
           //     change(parent,child,elem);
                int tmp=elem[parent];
                elem[parent]=elem[child];
                elem[child]=tmp;
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }
    }
    public void creatHeap(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i]=array[i];
            usedsize++;
        }
        for (int parent= (usedsize-1-1)/2; parent >=0; parent--) {
            shiftDown(parent,usedsize);
        }
    }
    private void shiftUp(int child) {
        int parent = (child-1)/2;
        while(parent>=0){
            if(elem[parent]<elem[child]){
                int tmp=elem[parent];
                elem[parent]=elem[child];
                elem[child]=tmp;
                child=parent;
                parent= (child-1)/2;
            }else {
                break;
            }
        }

    }

    public void offer(int val) {
        if(isFull()) {
            //扩容
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedsize++] = val;
        //注意这里传入的是usedSize-1
        shiftUp(usedsize-1);
    }

    public boolean isFull() {
        return usedsize == elem.length;
    }
    public  void poll(){
        if(isEmpty()){
            throw new RuntimeException("优先级队列为空");

        }

    }
    public  boolean isEmpty(){
        return usedsize==0;
    }
    public void heapSort(){
       int end=usedsize-1;
       change(0,end,this.elem);

       shiftDown(0,end);
        end--;
    }



}
